package cc.rengu.redp.bizimpl.upmp.controller;

import cc.rengu.redp.bizimpl.upmp.domain.BDeviceInfo;
import cc.rengu.redp.bizimpl.upmp.service.IBDeviceInfoService;
import cc.rengu.redp.bizimpl.upmp.vo.BDeviceInfoVO;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.redp.common.exception.RedpException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.wuwenze.poi.ExcelKit;
import com.wuwenze.poi.handler.ExcelReadHandler;
import com.wuwenze.poi.pojo.ExcelErrorField;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

/**
 * @author lizk
 */
@RestController
@RequestMapping("deviceInfo")
@Slf4j
public class BDeviceInfoController extends BaseController {

    @Autowired
    private IBDeviceInfoService ibDeviceInfoService;


    @GetMapping
    public Map<String, Object> findByPage(QueryRequest queryRequest, BDeviceInfo bDeviceInfo) {
        return getDataTable(ibDeviceInfoService.findByPage(queryRequest, bDeviceInfo));
    }

    @Log("新增设备")
    @PostMapping
//    @RequiresPermissions("brand:add")
    public void addDevice(@Valid BDeviceInfoVO bDeviceInfoVO) throws RedpException {

        try {
            this.ibDeviceInfoService.createDevice(bDeviceInfoVO);
        } catch (Exception e) {
            String message = e.getMessage();
            log.error(message, e);
            throw new RedpException(message);
        }

    }


    @Log("修改设备")
    @PutMapping
//    @RequiresPermissions("brand:update")
    public void updateDevice(BDeviceInfoVO bDeviceInfoVO) throws RedpException {
        try {
            this.ibDeviceInfoService.updateDevice(bDeviceInfoVO);
        } catch (Exception e) {
            String message = e.getMessage();
            log.error(message, e);
            throw new RedpException(message);
        }
    }


    /**
     * 生成 Excel导入模板
     */
    @PostMapping("downloadTemplate")
    public void generateImportTemplate(HttpServletResponse response) {
        // 构建数据
        List<BDeviceInfoVO> list = new ArrayList<>();
        IntStream.range(0, 1).forEach(i -> {
            BDeviceInfoVO bDeviceInfoVO = new BDeviceInfoVO();
            bDeviceInfoVO.setDeviceType("1-终端机具");
            bDeviceInfoVO.setDeviceDesc("额鹅鹅鹅");
            bDeviceInfoVO.setLibraryBatch("20200328001");
            bDeviceInfoVO.setModelCode("MD000006");
            bDeviceInfoVO.setBrandCode("BR000010");
            bDeviceInfoVO.setSn("G11201709");
            bDeviceInfoVO.setStartDate("20170101");
            bDeviceInfoVO.setEndDate("20170102");
            bDeviceInfoVO.setDevicePurchType("00-自用");
            bDeviceInfoVO.setDevicePrice("50");
            bDeviceInfoVO.setLeaseStartDate("20170101");
            bDeviceInfoVO.setLeaseEndDate("20170101");
            bDeviceInfoVO.setDeviceLeasePrice("50");
            bDeviceInfoVO.setCashPledge("50");


            bDeviceInfoVO.setContactName("upmp" + i + "@gmail.com");
            bDeviceInfoVO.setContactPhone("13800138000");
            bDeviceInfoVO.setContactEmail("upmp" + i + "@gmail.com");
            list.add(bDeviceInfoVO);
        });
        // 构建模板
        ExcelKit.$Export(BDeviceInfoVO.class, response).downXlsx(list, true);
    }

    /**
     * 导入Excel数据，并批量插入 T_TEST表
     */
    @PostMapping("import")
    public RedpResponse importExcels(@RequestParam("file") MultipartFile file, @RequestParam("instId") String instId) throws RedpException {
        try {
            if (file.isEmpty()) {
                throw new RedpException("导入数据为空");
            }
            String filename = file.getOriginalFilename();
            if (!StringUtils.endsWith(filename, ".xlsx")) {
                throw new RedpException("只支持.xlsx类型文件导入");
            }
            // 开始导入操作
            long beginTimeMillis = System.currentTimeMillis();
            final List<BDeviceInfoVO> data = Lists.newArrayList();
            final List<Map<String, Object>> error = Lists.newArrayList();
            ExcelKit.$Import(BDeviceInfoVO.class).readXlsx(file.getInputStream(), new ExcelReadHandler<BDeviceInfoVO>() {
                @Override
                public void onSuccess(int sheet, int row, BDeviceInfoVO test) {
                    Integer startDate = Integer.valueOf(test.getStartDate());
                    Integer endDate = Integer.valueOf(test.getEndDate());

                    Integer leaseStartDate = Integer.valueOf(test.getLeaseStartDate());
                    Integer leaseEndDate = Integer.valueOf(test.getLeaseEndDate());

                    List<ExcelErrorField> list = new ArrayList<>();
                    if (startDate <= endDate && leaseStartDate <= leaseEndDate){
                        test.setInstId(instId);
                        data.add(test);
                    }

                    if (startDate > endDate) {
                        list.add(new ExcelErrorField(7, test.getBrandName(), "有效期截止日期", "有效期截止日期不能早于有效期开始日期"));
                        error.add(ImmutableMap.of("row", row, "errorFields", list));
                    }

                    if (leaseStartDate > leaseEndDate){
                        list.add(new ExcelErrorField(15, test.getBrandName(), "租赁截止日期", "租赁截止日期不能早于租赁起始日期"));
                        error.add(ImmutableMap.of("row", row, "errorFields", list));
                    }

                }

                @Override
                public void onError(int sheet, int row, List<ExcelErrorField> errorFields) {
                    // 数据校验失败时，记录到 error集合
                    error.add(ImmutableMap.of("row", row, "errorFields", errorFields));
                }
            });
            if (!data.isEmpty()) {
                // 将合法的记录批量入库
                this.ibDeviceInfoService.batchInsert(data);
            }
            long time = ((System.currentTimeMillis() - beginTimeMillis));
            ImmutableMap<String, Object> result = ImmutableMap.of(
                    "time", time,
                    "data", data,
                    "error", error
            );
            return new RedpResponse().data(result);
        } catch (Exception e) {
            String message = "导入Excel数据失败," + e.getMessage();
            log.error(message);
            throw new RedpException(message);
        }
    }



}
